Union Types (|)
When you use a union type, you can create a type to be among many types, this indicates that one can choose from any of the assigned types.
Example: In the given below example we are defining Status with Union Types.
type Status = "success" | "error" | "loading";
function printStatus(status: Status) {
console.log(`The current status is: ${status}`);
}
printStatus("success");
printStatus("error");
printStatus("loading");
// Uncommenting this line will cause an error
// printStatus("complete");
Output:
The current status is: success
The current status is: error
The current status is: loading
Type Manipulation in TypeScript
TypeScript offers strong tools for types manipulation and transformation, these tools allow programmers to create new types by composing, intersecting, unionizing, mapping and conditioning existing ones, in this article we will investigate some of the advanced type-manipulation features in TypeScript including:
Table of Content
- Intersection Types (&)
- Union Types (|)
- Mapped Types
- Conditional Types